package com.s63.appinfo.util;

import com.s63.appinfo.pojo.LoginUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class SessionManager {
    private static SessionManager instance = new SessionManager();
    private Map<String, LoginUser> loginUserMap = new HashMap<>();

    private SessionManager() {}
    public static SessionManager getInstance() {
        return instance;
    }

    public void put(String uuid, LoginUser loginUser) {
        loginUserMap.put(uuid, loginUser);
    }

    public LoginUser getCurrentUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return loginUserMap.get(requestAttributes.getRequest().getHeader("token"));
    }

    public void del(String token) {
        loginUserMap.remove(token);
    }

    public static void main(String[] args) {

        String content = "you are my son"; // 原文
        try {
            System.out.println(new Byte("-15").byteValue());
            byte[] a;

            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            a = messageDigest.digest(content.getBytes());
            System.out.println(Base64.getEncoder().encodeToString(a));
            System.out.println(byte2hex(a)); // 333a9634d8809b5a9e8d280d82553b8fd8d4a911
            messageDigest = MessageDigest.getInstance("SHA-256");
            a = messageDigest.digest(content.getBytes());
            System.out.println(byte2hex(a)); // cdb2c97079d9a1943eea98de4201f5c4f49ecda5af2b364e1c7a5d1ae89688eb

            messageDigest = MessageDigest.getInstance("MD5");
            a = messageDigest.digest(content.getBytes());
            System.out.println(byte2hex(a)); // 6fe6b9a8f8bd29f4f4f1368a0619a7ae

//            // 第三方 MD5 算法。需要添加 jar 包 org.apache.commons.codec.digest.DigestUtils
//            String encodeStr= DigestUtils.md5Hex(content);
//            System.out.println(encodeStr); // 6fe6b9a8f8bd29f4f4f1368a0619a7ae

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String byte2hex(byte[] b) //二进制转字符串
    {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }
}
